package com.tl.branchmanagementdemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tl.branchmanagementdemo.Interface.StatementModifier;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import org.springframework.beans.BeanUtils;

import java.util.*;

public class IdentitySelectModifier implements StatementModifier {

    public IdentitySelectModifier() {
    }

    @Override
    public String modify(String sql, Statement statement, Object parameterObject) throws JSQLParserException {

        Select select = (Select) statement;

        PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
        PlainSelect plainSelect2 = getSelect(select);


        // Union将两个sql，凭借为一个sql
        SetOperationList setOperationList = new SetOperationList();
        SetOperation unionOp = new UnionOp();
        List<Boolean> brackets = Arrays.asList(false, false); // 将每个选择语句用括号包围
        setOperationList.setBracketsOpsAndSelects(brackets, Arrays.asList(plainSelect, plainSelect2), Collections.singletonList(unionOp));
        // 拼接子sql
        SubSelect subSelect = new SubSelect();
        subSelect.setSelectBody(setOperationList);
        String aliasTable = "unionTable";
        subSelect.setAlias(new Alias(aliasTable));

        PlainSelect plainSelectAll = new PlainSelect();
        plainSelectAll.setFromItem(subSelect);
        plainSelectAll.addSelectItems(new AllColumns());
        //以UNI_NO进行分组
        select.setSelectBody(plainSelectAll);
        //修改parameterObject
//        modifyParameterObject(parameterObject);
        return select.toString();
    }

    private void modifyParameterObject(Object parameterObject) {

        Map map = (Map) parameterObject;
        Set set = map.keySet();

        Map<String, Object> objectObjectHashMap = new HashMap<>();
        int size = map.keySet().size();
        size = size / 2;


        for (Object o : set) {
            String key = o.toString();
            if (key.startsWith("param")) {
                Object o1 = map.get(key);
                Object bean = BeanUtil.toBean(o1, Object.class);
                objectObjectHashMap.put("param" + (++size),bean);
            }
        }
        map.putAll(objectObjectHashMap);
    }

    private PlainSelect getSelect(Select select) throws JSQLParserException {
        String string = select.toString();
        Select selectRela = (Select) CCJSqlParserUtil.parse(string);
        PlainSelect selectRelaBody = (PlainSelect) selectRela.getSelectBody();
        return selectRelaBody;
    }

}
